package com.example.shushiyunsst

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.alibaba.fastjson.JSON
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO
import com.example.library_common.utils.even.TO_REFRESH_BALANCE_INFO_Failed
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import org.greenrobot.eventbus.EventBus

class BalanceInfoWork (context: Context, param: WorkerParameters) : Worker(context, param) {
    override fun doWork(): Result {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "sysWalletAddress" to userInfo?.sysWalletAddress
        )
        RestClient.builder()
            .url(R.string.wallet_index)
            .raw(JSON.toJSONString(maps))
            .success {
                val mBalanceInfoBean = JSON.parseObject(it, BalanceInfoBean::class.java)

                BalanceInfoManager.mBalanceInfoManager.saveUserInfoWrapper(mBalanceInfoBean)
                val msg = MessageWrap.getInstance(TO_REFRESH_BALANCE_INFO)
                msg.obj = mBalanceInfoBean
                EventBus.getDefault().post(msg)
            }
            .error { _, _ ->

                val msg = MessageWrap.getInstance(TO_REFRESH_BALANCE_INFO_Failed)

                EventBus.getDefault().post(msg)
            }
            .failure {
                val msg = MessageWrap.getInstance(TO_REFRESH_BALANCE_INFO_Failed)

                EventBus.getDefault().post(msg)
            }
            .build()
            .post()
        return Result.success()
    }
}